<?php

class PluginModel {
    public $pdo;
    
    public function __construct() {
        require_once __DIR__ . '/config.php';
        
        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
        $this->pdo = new PDO($dsn, DB_USER, DB_PASS);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        
        $this->initTables();
    }
    
    private function initTables() {
        // 插件表
        $this->pdo->exec("CREATE TABLE IF NOT EXISTS plugins (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) UNIQUE NOT NULL,
            title VARCHAR(200) NOT NULL,
            description TEXT,
            version VARCHAR(50),
            author VARCHAR(100),
            icon VARCHAR(200),
            is_active TINYINT(1) DEFAULT 1,
            view_count INT DEFAULT 0,
            like_count INT DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_name (name),
            INDEX idx_active (is_active),
            INDEX idx_views (view_count)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // 检查并添加缺失的字段
        try {
            $this->pdo->exec("ALTER TABLE plugins ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
        } catch (PDOException $e) {
            // 字段已存在，忽略错误
        }
        
        try {
            $this->pdo->exec("ALTER TABLE plugins ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
        } catch (PDOException $e) {
            // 字段已存在，忽略错误
        }
        
        // 分类表
        $this->pdo->exec("CREATE TABLE IF NOT EXISTS categories (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) UNIQUE NOT NULL,
            description TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_name (name)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // 插件分类关联表
        $this->pdo->exec("CREATE TABLE IF NOT EXISTS plugin_categories (
            id INT AUTO_INCREMENT PRIMARY KEY,
            plugin_id INT NOT NULL,
            category_id INT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE KEY unique_plugin_category (plugin_id, category_id),
            INDEX idx_plugin (plugin_id),
            INDEX idx_category (category_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // 尝试添加外键约束（如果不存在）
        try {
            $this->pdo->exec("ALTER TABLE plugin_categories ADD CONSTRAINT fk_plugin_id FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE");
        } catch (PDOException $e) {}
        
        try {
            $this->pdo->exec("ALTER TABLE plugin_categories ADD CONSTRAINT fk_category_id FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE");
        } catch (PDOException $e) {}
    }
    
    public function getPluginByName($name) {
        $stmt = $this->pdo->prepare("SELECT * FROM plugins WHERE name = ?");
        $stmt->execute([$name]);
        return $stmt->fetch();
    }
    
    public function getAllPlugins() {
        return $this->pdo->query("SELECT * FROM plugins ORDER BY created_at DESC")->fetchAll();
    }
    
    public function getAllPluginsData() {
        return $this->pdo->query("SELECT * FROM plugins ORDER BY view_count DESC")->fetchAll();
    }
    
    public function getActivePlugins() {
        return $this->pdo->query("SELECT * FROM plugins WHERE is_active = 1 ORDER BY view_count DESC")->fetchAll();
    }
    
    public function syncPlugin($pluginInfo) {
        $stmt = $this->pdo->prepare("
            INSERT INTO plugins (name, title, description, version, author, icon) 
            VALUES (?, ?, ?, ?, ?, ?) 
            ON DUPLICATE KEY UPDATE 
            title = VALUES(title), 
            description = VALUES(description), 
            version = VALUES(version), 
            author = VALUES(author), 
            icon = VALUES(icon),
            updated_at = CURRENT_TIMESTAMP
        ");
        return $stmt->execute([
            $pluginInfo['name'],
            $pluginInfo['title'],
            $pluginInfo['description'],
            $pluginInfo['version'],
            $pluginInfo['author'],
            $pluginInfo['icon'] ?? ''
        ]);
    }
    
    public function updatePluginStats($name, $viewCount = null, $likeCount = null) {
        $sql = "UPDATE plugins SET updated_at = CURRENT_TIMESTAMP";
        $params = [];
        
        if ($viewCount !== null) {
            $sql .= ", view_count = ?";
            $params[] = $viewCount;
        }
        
        if ($likeCount !== null) {
            $sql .= ", like_count = ?";
            $params[] = $likeCount;
        }
        
        $sql .= " WHERE name = ?";
        $params[] = $name;
        
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute($params);
    }
    
    public function incrementViewCount($name) {
        $stmt = $this->pdo->prepare("UPDATE plugins SET view_count = view_count + 1, updated_at = CURRENT_TIMESTAMP WHERE name = ?");
        return $stmt->execute([$name]);
    }
    
    public function incrementLikeCount($name) {
        $stmt = $this->pdo->prepare("UPDATE plugins SET like_count = like_count + 1, updated_at = CURRENT_TIMESTAMP WHERE name = ?");
        return $stmt->execute([$name]);
    }
    
    public function getCategories($asJson = false) {
        $cats = $this->pdo->query("SELECT * FROM categories ORDER BY id")->fetchAll();
        if ($asJson) return json_encode($cats);
        return $cats;
    }
    
    public function getPluginsByCategory($categoryId) {
        $stmt = $this->pdo->prepare("
            SELECT p.* FROM plugins p 
            JOIN plugin_categories pc ON p.id = pc.plugin_id 
            WHERE pc.category_id = ? AND p.is_active = 1 
            ORDER BY p.view_count DESC
        ");
        $stmt->execute([$categoryId]);
        return $stmt->fetchAll();
    }
    
    public function bindPluginToCategory($pluginId, $categoryId) {
        $stmt = $this->pdo->prepare("INSERT IGNORE INTO plugin_categories (plugin_id, category_id) VALUES (?, ?)");
        return $stmt->execute([$pluginId, $categoryId]);
    }
    
    public function unbindPluginFromCategory($pluginId, $categoryId) {
        $stmt = $this->pdo->prepare("DELETE FROM plugin_categories WHERE plugin_id = ? AND category_id = ?");
        return $stmt->execute([$pluginId, $categoryId]);
    }
    
    public function getPluginCategories($pluginId) {
        $stmt = $this->pdo->prepare("
            SELECT c.* FROM categories c 
            JOIN plugin_categories pc ON c.id = pc.category_id 
            WHERE pc.plugin_id = ?
        ");
        $stmt->execute([$pluginId]);
        return $stmt->fetchAll();
    }
    
    public function getStats() {
        $stats = [];
        
        // 总插件数
        $stmt = $this->pdo->query("SELECT COUNT(*) as count FROM plugins");
        $stats['total_plugins'] = $stmt->fetch()['count'];
        
        // 活跃插件数
        $stmt = $this->pdo->query("SELECT COUNT(*) as count FROM plugins WHERE is_active = 1");
        $stats['active_plugins'] = $stmt->fetch()['count'];
        
        // 总浏览量
        $stmt = $this->pdo->query("SELECT SUM(view_count) as total FROM plugins");
        $stats['total_views'] = $stmt->fetch()['total'] ?? 0;
        
        // 总点赞数
        $stmt = $this->pdo->query("SELECT SUM(like_count) as total FROM plugins");
        $stats['total_likes'] = $stmt->fetch()['total'] ?? 0;
        
        return $stats;
    }
    
    public function getTopPlugins($limit = 10) {
        $limit = (int)$limit; // 确保是整数
        $stmt = $this->pdo->prepare("SELECT * FROM plugins WHERE is_active = 1 ORDER BY view_count DESC LIMIT $limit");
        $stmt->execute();
        return $stmt->fetchAll();
    }
    
    public function searchPlugins($keyword) {
        $keyword = '%' . $keyword . '%';
        $stmt = $this->pdo->prepare("
            SELECT * FROM plugins 
            WHERE is_active = 1 AND (title LIKE ? OR description LIKE ?) 
            ORDER BY view_count DESC
        ");
        $stmt->execute([$keyword, $keyword]);
        return $stmt->fetchAll();
    }
} 